package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;

    //定义时间为一个月
    private static final Integer ONE_MONTH = 30;

    /*
    * 店铺营业额统计
    * */
    @Override
    public TurnoverReportVO findTurnoverStatistics(LocalDate begin, LocalDate end) {
        //统计时间dateList
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (true){
            if(begin.isAfter(end) || end.isEqual(begin)){
                break;
            }
            //将begin和end区间的时间添加进数组
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //统计营业额turnoverList
        List<BigDecimal> turnover = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer status = Orders.COMPLETED;

            //查询当天的营业额（状态为已完成的订单数之和）
            BigDecimal sumAmount = orderMapper.selectTurnoverByDate(beginTime, endTime, status);
            if (sumAmount == null){
                sumAmount = new BigDecimal("0.0");
            }
            turnover.add(sumAmount);
        }

        //封装turnoverReportVO对象
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(dateList,","));
        turnoverReportVO.setTurnoverList(StringUtils.join(turnover,","));

        return turnoverReportVO;
    }

    /*
    * 用户统计
    * */
    @Override
    public UserReportVO findUserStatistics(LocalDate begin, LocalDate end) {
        //查询dateList日期集合
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (true){
            //将begin和end区间的时间添加进数组
            if(begin.isAfter(end) || end.isEqual(begin)){
                break;
            }
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Long> newUserList = new ArrayList<>();
        List<Long> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("endTime", endTime);
            //查询totalUserList总用户集合
            Long totalUserCount = userMapper.selectUsersByDate(map);

            //查询newUserList新用户集合
            map.put("beginTime", beginTime);
            Long newUserCount = userMapper.selectUsersByDate(map);

            totalUserList.add(totalUserCount);
            newUserList.add(newUserCount);
        }

        //封装UserReportVO对象
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dateList,","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList,","));
        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        return userReportVO;
    }

    /*
    * 订单统计
    * */
    @Override
    public OrderReportVO findOrderStatistics(LocalDate begin, LocalDate end) {
        //封装dateList集合
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (true){
            //将begin和end区间的时间添加进数组
            if(begin.isAfter(end) || end.isEqual(begin)){
                break;
            }
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //创建返回的两个订单集合
        List<Long> orderCountList = new ArrayList<>();
        List<Long> validOrderCountList = new ArrayList<>();

        //统计订单总数
        Long totalOrderCount = 0L;
        //统计有效订单数
        Long validOrderCount = 0L;

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer status = Orders.COMPLETED;

            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);

            //封装orderCountList订单数列表集合
            Long totalOrder = orderMapper.selectOrdersByDate(map);
            orderCountList.add(totalOrder);
            //计算总订单数
            totalOrderCount = totalOrderCount + totalOrder;

            //封装validOrderCountList有效订单数列表
            map.put("status", status);
            Long totalValidOrder = orderMapper.selectOrdersByDate(map);
            validOrderCountList.add(totalValidOrder);
            //计算总有效订单数
            validOrderCount = validOrderCount + totalValidOrder;
        }

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate =validOrderCount.doubleValue() / totalOrderCount;
        }

        //封装OrderReportVO对象
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        orderReportVO.setTotalOrderCount(Math.toIntExact(totalOrderCount));
        orderReportVO.setValidOrderCount(Math.toIntExact(validOrderCount));

        return orderReportVO;


    }

    /*
     * 销量前十排行
     * */
    @Override
    public SalesTop10ReportVO findSalesTop10Statistics(LocalDate begin, LocalDate end) {
        /*//封装dateList集合
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (true){
            //将begin和end区间的时间添加进数组
            if(begin.isAfter(end) || end.isEqual(begin)){
                break;
            }
            begin = begin.plusDays(1);
            dateList.add(begin);
        }*/

        //创建返回的两个集合
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        Map map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);

        List<GoodsSalesDTO> salesTop10 = orderDetailMapper.selectSalesTop10ByDate(map);
        nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(StringUtils.join(nameList, ","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList, ","));

        return salesTop10ReportVO;
    }


    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < ONE_MONTH; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
